package banding.com.google.Zxing.scanview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.R;
import com.google.zxing.Result;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

import banding.com.google.Zxing.camera.CameraManager;
import banding.com.google.Zxing.decoding.CaptureActivityHandler;
import banding.com.google.Zxing.decoding.InactivityTimer;
import banding.com.google.Zxing.exceptions.FileCanNotReadException;
import banding.com.google.Zxing.utils.BarcodeUtils;
import banding.com.google.Zxing.utils.BitmapUtil;
import banding.com.google.Zxing.utils.StringRegex;
import banding.com.google.Zxing.view.ViewfinderView;
import banding.com.google.Zxing.view.WipeCardView;
import banding.com.google.Zxing.view.WipeCardView.WipeAnimationListener;

public class CaptureActivity extends Activity implements Callback, OnClickListener, OnCheckedChangeListener {


    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;

    private TextView btn_back;
    private CheckBox cb_lamp;
    private TextView btn_alum;
    private ProgressBar pb_progress;
    private WipeCardView wcv_resultCard;

    private BeepSoundMgr beepSoundMgr;

    /**
     * 扫描完成后，显示启动，要跳转的Activity的intent的key
     */
    public static final String KEY_VISIT_ACTIVITY_CLASS = "key-visit-activity-class";
    /**
     * 扫描完成后，要跳转的Activity的class
     */
    private Class<? extends Activity> visitActivityClass;

    /**
     * 扫描完成后，隐式启动，要跳转的Activity的intent的key
     */
    public static final String KEY_VISIT_ACTIVITY_ACTION = "key-visit-activity-action";
    private String visitActivityAction;


    public static void startIntent(Context packageContext, Intent intent) {
        intent.setClass(packageContext, CaptureActivity.class);
        packageContext.startActivity(intent);
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture);

        CameraManager.init(getApplication());

        assignViews();

        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepSoundMgr = BeepSoundMgr.newInstance(this);

        Intent intent = getIntent();
        visitActivityClass = (Class<? extends Activity>) intent.getSerializableExtra(KEY_VISIT_ACTIVITY_CLASS);
        visitActivityAction = intent.getStringExtra(KEY_VISIT_ACTIVITY_ACTION);
    }

    private void assignViews() {
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        btn_back = (TextView) findViewById(R.id.tv_back_capture);
        cb_lamp = (CheckBox) findViewById(R.id.cb_lamp_capture);
        btn_alum = (TextView) findViewById(R.id.tv_album_capture);
        pb_progress = (ProgressBar) findViewById(R.id.pb_progress_capture);
        wcv_resultCard = (WipeCardView) findViewById(R.id.wcv_resultCard_capture);


        btn_back.setOnClickListener(this);
        cb_lamp.setOnCheckedChangeListener(this);
        btn_alum.setOnClickListener(this);

        wcv_resultCard.setWipeListener(new WipeAnimationListener() {
            @Override
            public void onAnimation(Animation animation, int state) {
                if (state == WipeAnimationListener.WIPE_END){
                    wcv_resultCard.setVisibility(View.GONE);
                    handler.restartPreviewAndDecode();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        beepSoundMgr.setPlayBeep(true);
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            beepSoundMgr.setPlayBeep(false);
        }
        beepSoundMgr.initBeepSound();
        beepSoundMgr.setVibrate(true);

    }

    @Override
    protected void onPause() {
        super.onPause();
        pauseCamera();
    }

    public void pauseCamera() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        inactivityTimer.shutdown();
        beepSoundMgr.release();
    }

    /**
     * 处理扫描结果
     *
     * @param result 解析结果
     * @param barcode bitmap对象，已经被黑白处理过
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        beepSoundMgr.playBeepSoundAndVibrate();

        String resultString = result.getText();
        if (!TextUtils.isEmpty(resultString)) {

            /*
             *
             * 这里可以缓存bitmap到本地
             * String tempAbsolutePath = CoreBitmapTempMgr.tempToSd(barcode,"xxx");
             */
            String tempAbsolutePath = CoreBitmapTempMgr.tempToSd(barcode,"codenigeis/temp");
            Log.d(">>>",tempAbsolutePath);
            this.setResult(RESULT_OK, getIntent());

            if ((visitActivityClass != null) || (!TextUtils.isEmpty(visitActivityAction))) {
                Intent intent = new Intent();
                if (visitActivityClass != null) {
                    intent.setClass(this, visitActivityClass);
                }
                if (visitActivityAction != null) {
                    intent.setAction(visitActivityAction);
                }
                startActivity(intent);
                CaptureActivity.this.finish();
            }else{//否则直接在界面显示文字
                TextView tvResult = (TextView) findViewById(R.id.tv_resultText_capture);
                tvResult.setText(resultString);
                tvResult.setVisibility(View.VISIBLE);
                wcv_resultCard.setVisibility(View.VISIBLE);

            }
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private static final long VIBRATE_DURATION = 200L;
    private static final int IMAGE = 1;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_back_capture) {
            CaptureActivity.this.finish();

        } else if (i == R.id.tv_album_capture) {
            visitLocalAlbum();
        } else {
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        FlashlambMgr.clickView(this, isChecked);
    }

    /**
     * 访问本地相册选图
     */
    private void visitLocalAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        Log.d(">>>onActivityResult", requestCode + "---" + resultCode);
        if (requestCode == IMAGE) {

            switch (resultCode) {
                case Activity.RESULT_OK:
                    pareLocalAlbum(data);
                    break;
                case Activity.RESULT_CANCELED:
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 从本地相册解析
     * @param data
     */
    private void pareLocalAlbum(Intent data) {
        Log.d(">>>pareLocalAlbum", data + "");
        if (data == null) {
            return;
        }
        pauseCamera();
        pb_progress.setVisibility(View.VISIBLE);

        Uri selectedImage = data.getData();
        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePathColumns[0]);
        String imagePath = c.getString(columnIndex);
        c.close();
        File file = new File(imagePath);
        if (!file.exists()) {
            Toast.makeText(this, R.string.not_exist, Toast.LENGTH_LONG).show();
            return;
        } else {
            Bitmap bitmap = null;
            try {
                bitmap = BitmapUtil.loadBitmap(imagePath);
            } catch (FileCanNotReadException e) {
                e.printStackTrace();
            }
            if (bitmap == null) return;
            if (StringRegex.endWith(imagePath,"png",true)){
                bitmap = BitmapUtil.drawBackgroundColor(bitmap, Color.WHITE);
            }
            Result result = BarcodeUtils.parseCode(bitmap, "utf-8");//以utf-8解码
            if (result == null) {
                String text = getString(R.string.parse_fail);
                Toast.makeText(this, text, Toast.LENGTH_LONG).show();
            } else {
                String coreText = result.getText();
                Log.d(">>>", "解析结果：" + coreText);
            }
            try {
                if (bitmap != null){
                    bitmap.recycle();
                    bitmap = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pb_progress.setVisibility(View.GONE);
    }


}

